/**
 * @author HY
 * @create 2019.9.19
 */
import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Pagination, Popconfirm } from 'antd';
import Layouts from '../../components/Layout/Layout';
import Http from '../../components/_http';
import { HTTP_URL } from '../../common/config';

const { Search } = Input;

function List(props) {
  const [loading, setLoading] = useState(true);
  const [delItem, setDelItem] = useState('');
  const [search, setSearch] = useState('');
  const [table, setTable] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    if (loading) {
      Http.fetch({
        url: `${HTTP_URL.GET_TABLE_LIST}?search=${search}&page=${page}&per_page=30`,
        success(data) {
          setLoading(false);
          setPage(data.info.current_page);
          setTotal(data.info.total);
          setTable(data.info.data);
        }
      });
    }
    if (delItem) {
      Http.fetch({
        url: `${HTTP_URL.DELETE_FILE_URL}?id=${delItem}`,
        success(data) {
          setDelItem('');
          setLoading(true);
        }
      });
    }
  }, [loading, delItem]);

  function setColumns() {
    return [{
      title: '序号',
      width: 80,
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1
    }, {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (text, record, index) => <span dangerouslySetInnerHTML={{ __html: text }}></span>
    }, {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time'
    }, {
      title: '操作',
      dataIndex: 'visit_url',
      key: 'visit_url',
      render: (text, record, index) => {
        return (
          <div>
            <Button type="primary" href={text} target="_blank" style={{ marginRight: '10px' }}>查看文档</Button>
            <Popconfirm
              title="是否确认删除?"
              onConfirm={() => setDelItem(record.id)}
            >
              <Button type="danger">删除</Button>
            </Popconfirm>
          </div>
        )
      }
    }];
  }

  function handleSearch(value) {
    setSearch(value);
    setPage(1);
    setLoading(true);
  }

  function handlePageChange(page) {
    setPage(page);
    setLoading(true);
  }

  return (
    <Layouts>
      <Search
        style={{ marginBottom: 10 }}
        placeholder="请输入关键词"
        enterButton="搜索"
        onSearch={value => handleSearch(value)}
      />
      <Table rowKey="id" columns={setColumns()} dataSource={table} loading={loading} bordered pagination={false} />
      <div style={{ marginTop: 10, textAlign: 'right' }}>
        <Pagination showQuickJumper pageSize={30} current={page} total={total} onChange={handlePageChange} />
      </div>
    </Layouts>
  )
}

export default List;